package com.xw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.excel.EasyExcel;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.dao.UserDao;
import com.xw.entity.User;
import com.xw.exp.ServiceException;
import com.xw.jsr303Group.SaveGroup;
import com.xw.jsr303Group.UpdateGroup;
import com.xw.req.PageRequest;
import com.xw.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
/**
 * @Description: TODO
 * @Date: 2024/12/18 16:52
 * @Version: 1.0
 * @author 86151
 */
@RestController
@RequestMapping("user")
@Api(tags = "用户模块")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserDao userDao;


    @PostMapping("importExcel")
    @ApiOperation(value = "导入Excel表格数据")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result<>(Constants.ERROR, "文件不能为空");
        }

        // 简单校验文件后缀是否是Excel格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.toLowerCase().endsWith(".xlsx") && !fileName.toLowerCase().endsWith(".xls"))) {
            return new Result<>(Constants.ERROR, "请上传正确的Excel文件");
        }

        try {
            List<User> userList = EasyExcel.read(file.getInputStream()).head(User.class).sheet().doReadSync();
            userService.importUsers(userList);  // 导入用户数据
            return new Result<>(Constants.SUCCESS);
        } catch (ServiceException e) {
            // 捕获自定义异常并将错误信息返回给前端
            return new Result<>(Constants.ERROR, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(Constants.ERROR, "导入Excel数据失败");
        }
    }


    @GetMapping("exportExcel")
    @ApiOperation(value = "导出用户数据为Excel")
    public void exportExcel(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
        // 设置响应头信息，告诉浏览器这是一个Excel文件下载
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 从数据库获取用户数据列表
        List<User> userList = userService.listAllUsers();
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户列表").doWrite(userList);
    }

    @PostMapping("page")
    @ApiOperation(value = "用户列表")
    public Result<?> page(@RequestBody PageRequest<User> pageRequest) {
        return new Result<>(userService.page(pageRequest), Constants.SUCCESS);
    }


    @PostMapping("saveOrUpdate")
    @ApiOperation(value = "新增或修改用户")
    public Result<?> saveOrUpdate(@RequestBody @Validated({SaveGroup.class, UpdateGroup.class}) User user) {
        // 使用SensitiveWordHelper检查帖子内容是否包含敏感词
        if (SensitiveWordHelper.contains(user.getNickName())) {
            // 如果包含敏感词，返回错误信息
            return new Result<>(Constants.ERROR, "昵称包含敏感词，请重新填写");
        }
        if (SensitiveWordHelper.contains(user.getUserName())) {
            // 如果包含敏感词，返回错误信息
            return new Result<>(Constants.ERROR, "用户名包含敏感词，请重新填写");
        }
        if (user.getId() == null) {
            User userQueryEmail = new User();
            userQueryEmail.setEmail(user.getEmail());
            List<User> usersEmailList = userDao.selectAll(userQueryEmail);
            Optional<User> find = usersEmailList.stream().filter(u -> u.getEmail().equals(user.getEmail())).findAny();
            if (find.isPresent()) {
                throw new ServiceException(Constants.ERROR.getCode(), "邮箱已注册");
            }

            user.setPassword("123456");

            user.setPassword(DigestUtil.md5Hex(user.getPassword()));
            userDao.insert(user);
        } else {
            user.setPassword(null);
            userDao.updateById(user);
        }
        return new Result<>(Constants.SUCCESS);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("通过ID删除用户信息")
    public Result<?> deleteById(@PathVariable("id") Integer id) {
        userDao.deleteById(id);
        return new Result<>(Constants.SUCCESS);
    }

    @PostMapping("deleteBatchByIds")
    @ApiOperation("通过ID批量删除用户信息")
    public Result<?> deleteBatchByIds(@RequestBody List<Integer> ids) {
        userDao.deleteBatchByIds(ids);
        return new Result<>(Constants.SUCCESS);
    }


}
